<template>
  <div class="container">
    <div class="header">
      <div class="tabs flex flex-between">
        <div class="flex flex-center width-70" @click="setSort(0)">
          <span :class="sortIndex===0?'tab-on':'tab-off'">价格</span>
          <div class="mar-l-4">
            <img v-if="fileSpace && listQuery.sellPriceFlag===''" mode="widthFix" class="width-9 height-12"
              :src="fileSpace + '/images/goods-arrow3.png'"/>
            <img v-if="fileSpace && listQuery.sellPriceFlag===1" mode="widthFix" class="width-9 height-12"
              :src="fileSpace + '/images/goods-arrow1.png'"/>
            <img v-if="fileSpace && listQuery.sellPriceFlag===0" mode="widthFix" class="width-9 height-12"
              :src="fileSpace + '/images/goods-arrow2.png'"/>
          </div>
        </div>
       <div class="flex flex-center width-70" @click="setSort(1)">
          <span :class="sortIndex===1?'tab-on':'tab-off'">销量</span>
          <div class="mar-l-4">
            <img v-if="fileSpace && listQuery.salesNumSort===''" mode="widthFix" class="width-9 height-12"
              :src="fileSpace + '/images/goods-arrow3.png'"/>
            <img v-if="fileSpace && listQuery.salesNumSort===1" mode="widthFix" class="width-9 height-12"
              :src="fileSpace + '/images/goods-arrow1.png'"/>
            <img v-if="fileSpace && listQuery.salesNumSort===0" mode="widthFix" class="width-9 height-12"
              :src="fileSpace + '/images/goods-arrow2.png'"/>
          </div>
        </div>
        <div class="flex flex-center" @click="setSort(2)" v-if="fromType === 1">
          <div :class="sortIndex===2?'tab-on':'tab-off'" class="line-1 width-70 text-align-c">{{categoryName}}</div>
        </div>
      </div>
      <div class="mask" :class="{'mask-active': isExpend}" catchtouchmove="true" @click="isExpend = !isExpend"></div>
      <div class="category" :class="{'expend': isExpend}">
        <div class="category-list">
          <div class="list-item" :style="{backgroundColor: categoryIndex === index? '#ffe100' :'#fff', 
          color: categoryIndex === index  ? '#fff' : '#000', border:categoryIndex !== index? '1px solid #ccc' : ''}" 
          :class="{'item-active': categoryIndex === index}" 
          v-for="(item, index) in listCategory" :key="index" @click="categoryClick(item, index)">{{item.categoryName}}</div>
        </div>
      </div>
    </div>
    <div class="goods">
      <div class="goods-list">
        <div class="goods-wrap" v-for="(item, index) in listData" :key="index" @click="pageTo(item)">
          <div class="width-167 height-164 img-item-box pos-rel">
            <div v-if="item.stock === 0" class="sell-out">
              <div class="del-layer align-c">
                <div class="font-18">已售完</div>
                <div class="font-10 mar-t--2">SOLD OUT</div>
              </div>
            </div>
            <!-- 跨境图标 -->
            <div class="cross-border-pic">
              <!-- 跨境保税 -->
              <img
                v-if="fileSpace && item.crossBorderType === 2 && item.crossBorderLabelType === 1"
                :src="fileSpace + '/images/icon-cross-border.png'"
                class="icon-cross-border"
                alt="">
              <!-- 海外直邮 -->
              <img
                v-if="fileSpace && item.crossBorderType === 2 && item.crossBorderLabelType === 2"
                :src="fileSpace + '/images/icon-cross-border-22.png'"
                class="icon-cross-border"
                alt="">
            </div>
            <img v-if="item.mainImage" :src="item.mainImage" alt="" class="width-167 height-164">
          </div>
          <div class="goods-content pad-l-10 pad-r-10 pad-t-6">
            <div class="goods-title line-2 font-12">{{item.title}}</div>
            <div class="price-row flex flex-between mar-t-5 height-40">
              <div class="price-wrap">                
                <span v-if="getCustomerId && wholesaleAuthority" class="flex v-align-c">
                  <span class="font-10 pad-t-1">￥</span>
                  <span>{{ item.wholesalePrice }}</span>
                </span>
                <span v-else class="price cate-price min-short-w">
                  <img v-if="fileSpace" :src="fileSpace + '/images/unlock.png'" alt="" class="width-62 height-16">
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="pad-10 mar-t-10 align-c" v-if="nodata">
        <img v-if="fileSpace" mode="widthFix" class="width-153 height-75 nodata-img"
             :src="fileSpace + '/images/2-0-kong.png'"/>
        <div class="pad-t-20 font-14 font-gray">空空如也</div>
      </div>
    </div>
    <div class="foot-cart flex flex-between">
      <div class="content flex-item">
        <div class="flex flex-center">
          <van-icon class="mar-t--4" name="shopping-cart-o" size="22px" color="#999999" />
          <div class="font-13 mar-l-6">购物车<span v-if="cartBadge !== 0">({{cartBadge}})</span></div>
        </div>
        <div class="font-12 color-price">￥<span class="font-18">{{totalPrice}}</span></div>
      </div>
      <div class="go-cart" :style="{backgroundColor: '#ffe100', color: '#333333' }" @click="$pt.switchTab({url: '/pages/shop/cart/main'})">去购物车</div>
    </div>
  </div>
</template>
<script>
import { pageProjectGoodsByMemberId } from '@/api/home'
import { listNextCategoryByParentId, listMapShopCart } from '@/api/shop'
export default {
  data() {
    return {
      sortIndex: 0,
      categoryIndex: 0,
      isExpend: false,
      cartBadge: 0,
      // totalPrice: '0.00',
      listQuery: {
        sellPriceFlag: '',
        salesNumSort: ''
      },
      pullLoad: {
        loading: false,
        finished: false
      },
      listData: [],
      listCategory: [],
      goodsType: '',
      room_id: null,
      goods: {},
      skuPropList: [],
      skuList: [],
      values: [],
      params: {
        categoryId: '',
        memberId: '',
        customerId: '',
        currentPage: 1,
        size: 10
      },
      nodata: false,
      pageParams: {},
      fastGoods: [],
      goodsLoad: 0,
      globalStyle: {},
      categoryName: '全部',
      fromType: null, // 判断页面来源
      isGetUserInfo: false,
      isGetPhoneInfo: false,
      isAchieveCount: 0,
      effectiveList: [], // 有效商品
      noEffectiveList: [], // 失效商品
      shopCarParams: {
        memberId: '',
        customerId: ''
      },
      settlement: false,
      enterprise: {},
      wholesaleAuthority: ''
    }
  },
  computed: {
    totalPrice() {
      let price = '0.00'
      let wholesalePostFee = '0.00'
      this.cartBadge = 0
      this.listData.forEach(item => {
        this.effectiveList.forEach(cartItem => {
          cartItem.shoppingCartList.forEach(listItem => {
            if (listItem.goodsId === item.goodsId) {
              price = parseFloat(listItem.goodsPrice * 1 + price * 1).toFixed(2)
              this.cartBadge += listItem.goodsNum
            }
          })
          if (cartItem.goodsId === item.goodsId) {
            wholesalePostFee = parseFloat(cartItem.wholesalePostFee * 1 + wholesalePostFee * 1).toFixed(2)
          }
        })
      })
      price = parseFloat(price * 1 + wholesalePostFee * 1).toFixed(2)
      return price
    }
  },
  onLoad() {
    // 初始化data
    Object.assign(this.$data, this.$options.data())
    this.wholesaleAuthority = this.$pt.getStorageSync('wholesaleAuthority')
  },
  onShow() {
    /** fromType 判断页面来源 1: 从分类页面进来 2: 从链接跳转进来 */
    if (this.getCurrentPage().query.fromType) {
      this.fromType = Number(this.getCurrentPage().query.fromType)
    }
    if (this.fromType === 1) {
      this.pageParams = JSON.parse(this.getCurrentPage().query.params)
      this.params.categoryId = this.pageParams.enterpriseCategoryId
      this.params.memberId = this.getMemberId
      this.params.customerId = this.getCustomerId
      this.getCategoryList()
    }
    this.pageInit()
  },
  onPullDownRefresh() {
    // 下拉刷新
    this.$pt.pageScrollTo({
      scrollTop: 0,
      duration: 0
    })
    this.params.currentPage = 1
    this.listData = []
    this.pageInit()
    setTimeout(() => {
      this.$pt.stopPullDownRefresh()
    }, 500)
  },
  onReachBottom() {
    // 触底刷新
    if (!this.pullLoad.finished) {
      this.pageInit()
    }
  },
  methods: {
    listMapShopCart() {
      // 购物车列表请求
      this.shopCarParams.memberId = this.getCustomerId || this.getMemberId
      this.shopCarParams.customerId = this.getCustomerId
      this.$pt.showLoading()
      listMapShopCart(this.shopCarParams).then(response => {
        this.$pt.hideLoading()
        if (response.isError) return
        this.effectiveList = response.data.effectiveList
        this.noEffectiveList = response.data.noEffectiveList
        this.enterprise = response.data.enterprise
        // 判断是否属于阶梯价商品
        for (let goodsItem of response.data.effectiveList) {
          if ('ladderPriceList' in goodsItem) {
            this.$set(goodsItem, 'ladderAuth', 1)
            let curGoodsCount = 0
            goodsItem.shoppingCartList.forEach(item => {
              curGoodsCount += item.goodsNum
            })
            let tempArr = goodsItem.ladderPriceList.filter(filteritem => {
              return +filteritem.ladderNum <= +curGoodsCount
            })
            if (tempArr.length > 0) {
              // initGoodsLadderPrice为当前商品 初始数量所处的 阶梯价 (用于价格间差额的比较)
              this.$set(goodsItem, 'initGoodsLadderPrice', tempArr[tempArr.length - 1]['ladderPrice'])
              // curGoodsPrice 当前商品数量所处的阶梯价 (用于页面上显示当前商品价格)
              this.$set(goodsItem, 'curGoodsPrice', tempArr[tempArr.length - 1]['ladderPrice'])
            } else {
              this.$set(goodsItem, 'initGoodsLadderPrice', goodsItem.ladderPriceList[0]['ladderPrice'])
              this.$set(goodsItem, 'curGoodsPrice', goodsItem.ladderPriceList[0]['ladderPrice'])
            }
            let tempLadderPriceList = []
            let i
            for (let index in goodsItem.ladderPriceList) {
              if (goodsItem.ladderPriceList[index]['ladderPrice'] === goodsItem.curGoodsPrice) {
                this.$set(goodsItem.ladderPriceList[index], 'isActive', true)
                this.$set(goodsItem, 'curIndex', parseInt(index / 3))
              } else {
                this.$set(goodsItem.ladderPriceList[index], 'isActive', false)
              }
              if (index % 3 === 0) {
                i = parseInt(index / 3)
                tempLadderPriceList[i] = []
              }
              tempLadderPriceList[i].push(goodsItem.ladderPriceList[index])
            }
            this.$set(goodsItem, 'tempLadderPriceList', tempLadderPriceList)
            // showDifference为是否显示差额信息
            this.$set(goodsItem, 'showDifference', false)
          } else {
            this.$set(goodsItem, 'ladderAuth', 0)
          }
        }
        this.effectiveList.forEach(item => {
          item.checked = false
          item.isAchieve = true
          item.shoppingCartList.forEach(skuItem => {
            skuItem.checked = false
          })
        })
      })
    },
    pageInit() {
      this.listMapShopCart()
      /** 从分类页进入请求相对于的分类信息  从链接进入请求所有商品信息 */
      this.nodata = false
      if (this.fromType === 1) {
        if (this.listQuery.sellPriceFlag !== '') {
          this.params.sellPriceSort = this.listQuery.sellPriceFlag
          this.params.salesNumSort = ''
        }
        if (this.listQuery.salesNumSort !== '') {
          this.params.salesNumSort = this.listQuery.salesNumSort
          this.params.sellPriceSort = ''
        }
        pageProjectGoodsByMemberId(this.params).then(response => {
          if (response.isError) return
          response.data.records.forEach(element => {
            this.listData.push(element)
          })
          if (this.listData.length === 0) this.nodata = true
          this.params.currentPage++
          if (this.listData.length === 0 || this.listData.length >= response.data.total) {
            this.pullLoad.finished = true
          }
        }).catch(() => {
        })
      }
    },
    // 头像昵称 授权后 立即跳出手机号授权
    authPhoneInfo() {
      this.isGetPhoneInfo = true
    },
    getCategoryList() {
      let params = {
        enterpriseCategoryId: this.pageParams.upperEnterpriseCategoryId
      }
      listNextCategoryByParentId(params).then(response => {
        if (response.isError) return
        this.listCategory = response.data
        // 手动添加全部分类
        this.listCategory.unshift({
          categoryName: '全部',
          enterpriseCategoryId: this.listCategory[0].parentId
        })
        this.listCategory.forEach((item, index) => {
          if (item.enterpriseCategoryId === this.params.categoryId) {
            this.categoryIndex = index
            this.categoryName = item.categoryName
          }
        })
      }).catch(() => {
      })
    },
    resetPageParams() {
      this.listData = []
      this.params.currentPage = 1
      this.pullLoad.finished = false
      this.pageInit()
    },
    setSort(value) {
      this.sortIndex = value
      switch (this.sortIndex) {
        case 0:
          this.listQuery.sellPriceFlag = this.listQuery.sellPriceFlag ? 0 : 1
          this.listQuery.salesNumSort = ''
          this.resetPageParams()
          this.isExpend = false
          break
        case 1:
          this.listQuery.salesNumSort = this.listQuery.salesNumSort ? 0 : 1
          this.listQuery.sellPriceFlag = ''
          this.resetPageParams()
          this.isExpend = false
          break
        case 2:
          this.listQuery.sellPriceFlag = ''
          this.listQuery.salesNumSort = ''
          this.isExpend = !this.isExpend
          break
        default:
          break
      }
    },
    categoryClick(item, index) {
      this.categoryIndex = index
      this.categoryName = item.categoryName
      this.isExpend = false
      console.log('点击分类', item)
      this.listData = []
      this.params.currentPage = 1
      this.pullLoad.finished = false
      this.params.categoryId = item.enterpriseCategoryId
      this.resetPageParams()
    },
    pageTo(item) {
      this.$pt.navigateTo({url: '/pages/shop/detail/main?goodsId=' + item.goodsId + '&goodsType=' + item.goodsType})
    }
  }
}
</script>
<style lang="less" scoped>
.container {
  min-height: 100vh;
  background: white;
  .header {
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 99;
    .tabs {
      background-color: white;
      height: 50px;
      padding: 0 15px;
      justify-content: space-around;
      border-bottom: 1px solid transparent;
      border-image: linear-gradient(to bottom, transparent 50%, #eeeeee 50%) 0 0
        100%/1px 0;
      .tab-on {
        color: #333333;
        font-size: 14px;
      }
      .tab-off {
        color: #999999;
        font-size: 14px;
      }
    }
    .mask {
      height: 0;
      width: 100%;
      position: absolute;
      left: 0;
      right: 0;
      z-index: 1;
    }
    .mask-active {
      height: 100vh;
    }
    .category {
      z-index: 9;
      position: absolute;
      width: calc(100% - 30px);
      left: 0;
      top: 47px;
      padding: 0 15px;
      background-color: white;
      height: 0px;
      overflow: hidden;
      .category-list {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;
        padding-bottom: 6.5px;
        .list-item {
          width: 76px;
          padding: 0 3px;
          box-sizing: border-box;
          height: 32px;
          text-align: center;
          border-radius: 16px;
          font-size: 12px;
          line-height: 32px;
          background-color: #f5f5f5;
          margin-right: calc((100% - 304px) / 3);
          margin-bottom: 10px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          word-break: break-word;
          &:nth-child(4n + 4) {
            margin-right: unset;
          }
        }
        .item-active {
          background-color: #ffe200;
        }
      }
    }
    .expend {
      height: auto;
    }
  }
  .img-item-box {
    .sell-out {
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      color: rgba(254, 254, 254, 0.7);
      background: rgba(0, 0, 0, 0.5);
      font-size: 12px;
      .del-layer {
        border-radius: 50%;
        border: 1px solid white;
        justify-content: center;
        width: 90px;
        height: 90px;
      }
      .delete-css {
        position: absolute;
        transform: rotate(-45deg);
        background: rgba(255, 255, 255, 0.58);
        height: 20px;
        line-height: 20px;
        font-size: 12px;
        width: 100%;
        text-align: center;
        color: #000;
      }
    }
  }
  .goods {
    padding-top: 51px;
    padding-bottom: 49px;
    .goods-list {
      padding: 15px 15px 0;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-wrap: wrap;
      width: calc(100% - 30px);
      .goods-wrap {
        width: 167px;
        height: 251px;
        background-color: white;
        border-radius: 8px;
        box-shadow: 0 0 6px 1px rgba(93, 93, 93, 0.2);
        margin-right: calc(100% - 334px);
        margin-bottom: 15px;
        overflow: hidden;
        &:nth-child(2n + 2) {
          margin-right: unset;
        }
        .goods-content {
          .price-row {
            .price-wrap {
              color: #ff593e;
              display: flex;
              justify-content: flex-start;
              align-items: center;
              line-height: 1;
            }
          }
          .price-short {
            max-width: 50px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            word-break: break-word;
          }
        }
      }
    }
  }
  .foot-cart {
    position: fixed;
    height: 49px;
    width: 100%;
    background-color: white;
    left: 0;
    bottom: 0;
    box-shadow: 0 0 5px rgba(155, 155, 155, 0.15);
    .content {
      padding-left: 15px;
      padding-right: 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .color-price {
        color: #ff593e;
      }
    }
    .go-cart {
      font-size: 16px;
      background-color: #ffe200;
      height: 49px;
      line-height: 49px;
      width: 133.5px;
      text-align: center;
    }
  }
}
.nodata-img {
  margin-left: 30px;
  margin-top: 80px;
}
/deep/ .goods-step {
  .van-stepper__minus,
  .van-stepper__plus {
    width: 36px;
    height: 36px;
  }
  .van-stepper__input-wrapper {
    width: 16px;
    height: 36px;
    border: transparent;
    font-size: 12px;
    color: #333;
    background: transparent;
    background-color: transparent;
  }
  .van-stepper__input {
    background-color: transparent;
    background: transparent;
    border: transparent;
  }
  .van-stepper__minus:after,
  .van-stepper__minus:before {
    background-color: #fed806;
  }
  .van-stepper__plus:after,
  .van-stepper__plus:before {
    background-color: #fff;
  }
  .van-stepper__minus {
    background-color: none;
    border-radius: 100px;
    border: none;
    background: url('https://veekrayimg.joinsun.vip/images/buy-sty-13.png')
      no-repeat center;
    background-size: 22px 23px;
  }
  .van-stepper__plus {
    background-color: none;
    border-radius: 100px;
    border: none;
    background: url('https://veekrayimg.joinsun.vip/images/buy-sty-10.png')
      no-repeat center;
    background-size: 22px 23px;
  }
  .van-stepper__minus--disabled,
  .van-stepper__plus--disabled {
    opacity: 0.3;
  }
  .van-stepper__minus--hover {
    opacity: 0.4;
  }
  .van-stepper__plus--hover {
    opacity: 0.5;
  }
}
</style>
